import Util from "../../../StartAb/Util";
import WXAD from "../../../StartAb/WXAd";
import WXRealLogUtil from "../../../StartAb/WXRealLogUtil";
import CocosHelper from "../../TFrame/script/helper/CocosHelper";
import EventCenter from "../../TFrame/script/helper/EventCenter";
import Coordinates from "../Coordinates";
import EventNames from "../EventNames";
import GardenSystem from "../garden/GardenSystem";
import NativeCaller from "../NativeCaller";
import { ActionType } from "../net/Enum";
import ServiceLogic from "../net/ServerLogic";
import PlayerDataMgr from "../PlayerDataMgr";
import ResManager from "../ResManager";
import GameLogicController from "./GameLogicController";

const { ccclass, property } = cc._decorator;
//@ts-ignore
const i18n = require('LanguageData');

@ccclass
export default class GameEndView extends cc.Component {

    @property(cc.Label)
    levelNumLabel: cc.Label = null;

    @property(cc.Label)
    errorNumLabel: cc.Label = null;

    @property(cc.Node)
    highlightStarRoot: cc.Node = null;

    @property(cc.Label)
    greatNiceLabel: cc.Label = null;

    @property(cc.Node)
    totalStarNode: cc.Node = null;

    @property(cc.Label)
    rewardLevel: cc.Label = null;

    @property(cc.ProgressBar)
    rewardLevelProgressbar: cc.ProgressBar = null;

    @property(cc.SpriteFrame)
    sunshineFrame: cc.SpriteFrame = null;

    @property(cc.Node)
    btnGardenNode: cc.Node = null;

    @property({ type: [cc.Button] })
    buttons: cc.Button[] = []

    protected onEnable(): void {
        WXAD.instance.showBanner()
    }

    protected onDisable(): void {
        WXAD.instance.hideBanner()
    }

    start() {
        this.errorNumLabel.string = GameLogicController.getInstance().errorCount.toString();
        let star = GameLogicController.getInstance().calStarCount();

        PlayerDataMgr.getInstance().updateLevelStar(ResManager.currentLevelIndex, star)

        PlayerDataMgr.getInstance().addScore(star);

        PlayerDataMgr.getInstance().passLevel();
        GardenSystem.addSunshine(1);

        for (let i = 1; i <= star; ++i) {
            let starNode = this.highlightStarRoot.getChildByName(i.toString());
            this.scheduleOnce(() => {
                starNode.opacity = 255;
                if (i == star) {
                    this.flySunshine()
                    this.flyStarAddCount(star)
                }
            }, 0.3 * i)
        }
        let workKeys = ['notbad', 'nice', 'perfect'];
        this.scheduleOnce(() => {
            this.greatNiceLabel.string = i18n.t(workKeys[star - 1])
        }, star * 0.3 + 0.3)

        WXRealLogUtil.info(`通过第${ResManager.currentLevelIndex + 1}关`)

        this.showRewardProgressInfo();
        this.showFull();
        this.disableButtons();
        PlayerDataMgr.getInstance().persist();

        if (ResManager.autoTestLevels == true) {
            this.scheduleOnce(() => {
                this.next(null);
            }, 1)
        }
    }

    Reward_Level_Cnt = 5;
    showRewardProgressInfo() {
        this.rewardLevelProgressbar.progress = (PlayerDataMgr.getInstance().level_pass_reward_idx - 1) / this.Reward_Level_Cnt;
        this.rewardLevel.string = (PlayerDataMgr.getInstance().level_pass_reward_idx - 1) + "/" + this.Reward_Level_Cnt;
        this.scheduleOnce(() => {
            this.rewardLevel.string = (PlayerDataMgr.getInstance().level_pass_reward_idx) + "/" + this.Reward_Level_Cnt;
        }, 0.25)
        cc.tween(this.rewardLevelProgressbar)
            .to(0.5, { progress: PlayerDataMgr.getInstance().level_pass_reward_idx / this.Reward_Level_Cnt })
            .call(() => {
                if (PlayerDataMgr.getInstance().level_pass_reward_idx >= this.Reward_Level_Cnt) {
                    PlayerDataMgr.getInstance().level_pass_reward_idx = 0;
                    PlayerDataMgr.getInstance().persistLevelPassRewardIdx();
                    //drop box
                    this.dropBox();
                }
                this.enableButtons();
            })
            .start()
    }

    disableButtons() {
        this.buttons.forEach((btn: cc.Button) => {
            btn.interactable = false;
        })
    }

    enableButtons() {
        this.buttons.forEach((btn: cc.Button) => {
            btn.interactable = true;
        })

        if (PlayerDataMgr.getInstance().autoPlay == true) {
            this._nextDo()
        }
    }

    dropBox() {
        cc.assetManager.getBundle("GameAb").load("prefab/LevelRewardDropBox", cc.Prefab, (err: Error, pf: cc.Prefab) => {
            if (err) {
                WXRealLogUtil.error(`加载资源出错:${err.message}`)
                return console.log(err.message);
            }
            let dialog = cc.instantiate(pf);
            if (this.isValid)
                dialog.parent = this.node;
        })
    }

    flyStarAddCount(star: number) {
        let node = new cc.Node;
        let lb = node.addComponent(cc.Label);
        node.parent = this.node;
        lb.string = "+" + star.toString();
        lb.fontSize = 50;
        node.color = cc.Color.GREEN;
        node.position = this.highlightStarRoot.position;
        cc.tween(node).to(0.5, { x: this.totalStarNode.x + 100, y: this.totalStarNode.y - 60 })
            .call(() => {
            })
            .delay(0.2).call(() => {
                EventCenter.emit(EventNames.StarCountChange);
                cc.tween(node).to(1, { opacity: 0 }).call(() => {
                    node.active = false
                }).start();
            }).start();
    }

    flySunshine() {
        let node = new cc.Node;
        let spr = node.addComponent(cc.Sprite);
        spr.spriteFrame = this.sunshineFrame;
        node.parent = this.node;
        node.position = this.highlightStarRoot.position;
        cc.tween(node).to(0.5, { x: this.btnGardenNode.x, y: this.btnGardenNode.y - 60 })
            .call(() => {
                EventCenter.emit(EventNames.UpdateSunshineButton)
                node.destroy();
            }).start();
    }

    home(e: cc.Event.EventTouch) {
        ResManager.currentLevelIndex = ResManager.getNextLevel();
        PlayerDataMgr.getInstance().setLastLevelIndex(ResManager.currentLevelIndex)
        Util.changeScene(PlayerDataMgr.isADVideo ? 'levelList_ad' : "Home");
        CocosHelper.disableButton(e);
    }

    tryAgain(e: cc.Event.EventTouch) {
        Util.changeScene('game');
        CocosHelper.disableButton(e);
    }

    next(e: cc.Event.EventTouch) {
        this._nextDo()
        CocosHelper.disableButton(e);
    }

    _nextDo() {
        ResManager.currentLevelIndex = ResManager.getNextLevel();
        PlayerDataMgr.getInstance().setLastLevelIndex(ResManager.currentLevelIndex)
        Coordinates.loadLvCoordinate(ResManager.currentLevelIndex, () => {
            Util.changeScene(PlayerDataMgr.isADVideo ? "game_ad" : "game");
        })
    }

    showFull() {
        if (PlayerDataMgr.getInstance().notShowFullLevelCount >= 1) {
            NativeCaller.showFull();
            PlayerDataMgr.getInstance().notShowFullLevelCount = 0;
            return
        }
        PlayerDataMgr.getInstance().notShowFullLevelCount += 1;
    }
}
